
let ISWECHAT = true
cc.Class({
    extends: cc.Component,

    properties: {
        rankContent: cc.Node,
        levelRankContent: cc.Node,
        rankItem: cc.Prefab,
        content: cc.Node,
        headImage: cc.Prefab,
        _hasRenderLevelList: false,
        _hasRenderwuJinList: false,
        btnShowArr: {
            default: [],
            type: cc.Node
        },
    },

    start() {
        if (ISWECHAT) {
            window.wx.onMessage(this.parseData.bind(this));
        } else {
            this.parseData({ messageType: -1, openId: 'sadfsdg2' })
            this.parseData({ messageType: 2, openType: 'score' })
        }
    },

    parseData(data) {
        this._hasRenderLevelList = false;
        this._hasRenderwuJinList = false;
        this.data = data;
        console.log("接收主域发来消息：", data)
        if (data.messageType == -1) {
            this.openId = data.openId;
        } else if (!this.openId) {
            console.error('openId is null')
        }
        if (data.messageType == 0) {
            this.resetScene();
        } else if (data.messageType == 1) {
            this.submitScore(data.openType, data.score);
        } else if (data.messageType == 2) {     //显示无尽排名
            this.fetchFriendData(data.openType, this.showRank.bind(this));
            //默认显示关卡排名            
            // this.fetchLevelData('level', this.showLevelRank.bind(this));
        } else if (data.messageType == 3) {     //即将超越的好友头像
            this.fetchFriendData(data.openType, this.showSurpass.bind(this));
        } else if (data.messageType == 4) {     //显示即将超越的好友头像
            this.showSurpass(this.friendData, data.score);
        } else if (data.messageType == 5) {  //显示场景排名
            this.positionData = data.plotDescCfg;
            cc.log(' this.positionData', this.positionData)
            this.fetchFriendPlotData(data.openType, this.showFriendHead.bind(this));
        } else if (data.messageType == 6) {     //提交场景分数
            this.submitPlotScore(data.openType, data.plotId, data.score);
        }
    },

    submitScore(openType, score) { //提交得分
        if (ISWECHAT) {
            window.wx.getUserCloudStorage({
                // 以key/value形式存储
                keyList: ['selfOpenId'],
                success: function (getres) {
                    console.log('getUserCloudStorage', 'success', getres)
                    if (getres.KVDataList.length != 0) {
                        if (getres.KVDataList[0].value > score) {
                            return;
                        }
                    }
                    // 对用户托管数据进行写数据操作
                    window.wx.setUserCloudStorage({
                        KVDataList: [{ key: openType, value: "" + score }],
                        success: function (res) {
                            console.log('setUserCloudStorage', 'success', res)
                        },
                        fail: function (res) {
                            console.log('setUserCloudStorage', 'fail')
                        },
                        complete: function (res) {
                            console.log('setUserCloudStorage', 'ok')
                        }
                    });
                },
                fail: function (res) {
                    console.log('getUserCloudStorage', 'fail')
                },
                complete: function (res) {
                    console.log('getUserCloudStorage', 'ok')
                }
            });
        } else {
            cc.log("提交得分:" + openType + " : " + score)
        }
    },

    submitPlotScore(openType, plotId, score) { //提交得分
        if (ISWECHAT) {
            window.wx.getUserCloudStorage({
                // 以key/value形式存储
                keyList: ['selfOpenId'],
                success: function (getres) {
                    console.log('getUserCloudStorage', 'success', getres)
                    if (getres.KVDataList.length != 0) {
                        if (getres.KVDataList[0].value > score) {
                            return;
                        }
                    }
                    // 对用户托管数据进行写数据操作
                    let value = JSON.stringify({ score: score, plotId: plotId })
                    window.wx.setUserCloudStorage({
                        KVDataList: [{ key: openType, value: value }],
                        success: function (res) {
                            console.log('setUserCloudStorage', 'success', res)
                        },
                        fail: function (res) {
                            console.log('setUserCloudStorage', 'fail')
                        },
                        complete: function (res) {
                            console.log('setUserCloudStorage', 'ok')
                        }
                    });
                },
                fail: function (res) {
                    console.log('getUserCloudStorage', 'fail')
                },
                complete: function (res) {
                    console.log('getUserCloudStorage', 'ok')
                }
            });
        } else {
            cc.log("提交剧情关卡得分:" + openType + " : " + score)
        }
    },

    fetchFriendData(openType, callback) {
        if (this.friendData) {
            return callback(this.friendData)
        }
        var self = this;
        var sortData = function (res) {
            if (!res) {
                return callback(null)
            }
            res.data.sort((a, b) => {
                if (a.KVDataList.length == 0 && b.KVDataList.length == 0) {
                    return 0;
                }
                if (a.KVDataList.length == 0) {
                    return 1;
                }
                if (b.KVDataList.length == 0) {
                    return -1;
                }
                return b.KVDataList[0].value - a.KVDataList[0].value;
            });
            self.friendData = res.data;
            callback(res.data);
        }
        if (ISWECHAT) {
            wx.getUserInfo({
                openIdList: [this.openId],
                success: (userRes) => {
                    //取出所有好友数据
                    wx.getFriendCloudStorage({
                        keyList: [openType],
                        success: sortData,
                        fail: res => {
                            console.log("wx.getFriendCloudStorage fail", res);
                            // this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                            callback(null)
                        },
                    });
                },
                fail: (res) => {
                    // this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                    callback(null)
                }
            })
        } else {
            let userData = { nickname: "徐小燕11" };
            let data = new Array();
            for (let i = 0; i < 13; i++) {
                data[i] = {
                    KVDataList: [{ key: "x1", value: "12" + i }],
                    avatarUrl: "https://wx.qlogo.cn/mmopen/vi_32/9h9G1VucURhfeXmbIicrXRnuJAvxdBfAC3xeSvfvjsYAfhJahJvU9ic2dTUpn5icLich8QDGeB0ojwUWfJia16O1yXQ/132",
                    nickname: "徐小燕" + i,
                    openid: "sadfsdg" + i,
                    sex: i % 2
                }
            }
            sortData({ data: data });
        }
    },
    fetchLevelData(openType, callback) {
        var self = this;
        var sortData = function (res) {
            cc.log('所有plotId取出的好友数据', res);
            if (!res) {
                return callback(null)
            }
            let hasData = [];
            res.data.forEach(element => {
                if (element.KVDataList.length > 0 && JSON.parse(element.KVDataList[0].value).plotId) hasData.push(element);
            });
            hasData.sort((a, b) => {
                if (a.KVDataList.length == 0 && b.KVDataList.length == 0) {
                    return 0;
                }
                if (a.KVDataList.length == 0) {
                    return 1;
                }
                if (b.KVDataList.length == 0) {
                    return -1;
                }
                cc.log(JSON.parse(b.KVDataList[0].value).plotId);
                cc.log(JSON.parse(a.KVDataList[0].value).plotId);
                return JSON.parse(b.KVDataList[0].value).plotId - JSON.parse(a.KVDataList[0].value).plotId;
            });
            self.friendPlotData = hasData;
            callback(hasData);
        }
        if (ISWECHAT) {
            wx.getUserInfo({
                openIdList: [this.openId],
                success: (userRes) => {
                    //取出所有好友数据
                    wx.getFriendCloudStorage({
                        keyList: [openType],
                        success: sortData,
                        fail: res => {
                            console.log("wx.getFriendCloudStorage fail", res);
                            // this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                            callback(null)
                        },
                    });
                },
                fail: (res) => {
                    // this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                    callback(null)
                }
            })
        } else {
            let userData = { nickname: "徐小燕11" };
            let data = new Array();
            for (let i = 0; i < 13; i++) {
                data[i] = {
                    KVDataList: [{ key: "x1", value: '{"plotId":"0","score":"20"}' }],
                    avatarUrl: "https://wx.qlogo.cn/mmopen/vi_32/9h9G1VucURhfeXmbIicrXRnuJAvxdBfAC3xeSvfvjsYAfhJahJvU9ic2dTUpn5icLich8QDGeB0ojwUWfJia16O1yXQ/132",
                    nickname: "徐小燕" + i,
                    openid: "sadfsdg" + i,
                    sex: i % 2
                }
            }
            sortData({ data: data });
        }
    },

    fetchFriendPlotData(openType, callback) {
        var self = this;
        var sortData = function (res) {
            cc.log('所有plotId取出的好友数据', res);
            if (!res) {
                return callback(null)
            }
            let hasData = [];
            res.data.forEach(element => {
                if (element.KVDataList.length > 0) hasData.push(element);
            });
            hasData.sort((a, b) => {
                if (a.KVDataList.length == 0 && b.KVDataList.length == 0) {
                    return 0;
                }
                if (a.KVDataList.length == 0) {
                    return 1;
                }
                if (b.KVDataList.length == 0) {
                    return -1;
                }
                return JSON.parse(b.KVDataList[0].value).plotId - JSON.parse(a.KVDataList[0].value).plotId;
            });
            self.friendPlotData = hasData;
            callback(hasData);
        }
        if (ISWECHAT) {
            wx.getUserInfo({
                openIdList: [this.openId],
                success: (userRes) => {
                    //取出所有好友数据
                    wx.getFriendCloudStorage({
                        keyList: [openType],
                        success: sortData,
                        fail: res => {
                            console.log("wx.getFriendCloudStorage fail", res);
                            this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                            callback(null)
                        },
                    });
                },
                fail: (res) => {
                    this.loadingLabel.string = "数据加载失败，请检测网络，谢谢。";
                    callback(null)
                }
            })
        } else {
            let userData = { nickname: "徐小燕11" };
            let data = new Array();
            for (let i = 0; i < 13; i++) {
                data[i] = {
                    KVDataList: [{ key: "x1", value: '{"plotId":"0","score":"20"}' }],
                    avatarUrl: "https://wx.qlogo.cn/mmopen/vi_32/9h9G1VucURhfeXmbIicrXRnuJAvxdBfAC3xeSvfvjsYAfhJahJvU9ic2dTUpn5icLich8QDGeB0ojwUWfJia16O1yXQ/132",
                    nickname: "徐小燕" + i,
                    openid: "sadfsdg" + i,
                    sex: i % 2
                }
            }
            sortData({ data: data });
        }
    },


    resetScene() {
        for (var i = 0; i < this.node.children.length; i++) {
            this.node.children[i].active = false;
        }
    },

    findAfterData(data, score) { //查找比我value大一级的好友 如果有提交分数，就检测分数，否则只检测自己排位
        var after = data[0];
        for (var i = 1; i < data.length; i++) {
            if (score) {
                let s = data[i].KVDataList[0] ? data[i].KVDataList[0].value : 0;
                if (score < parseInt(s)) {
                    break;
                }
            } else if (data[i].openid == this.openId) {
                break;
            }
            after = data[i]
        }
        return after;
    },

    showSurpass(data, score) {
        if (!data) {
            return;
        }
        this.node.getChildByName('Surpass').active = true;
        var passnode = this.node.getChildByName('Surpass')
        var lastData = this.findAfterData(data, score);
        passnode.getChildByName('name').getComponent(cc.Label).string = lastData.nickname;
        let s = lastData.KVDataList[0] ? lastData.KVDataList[0].value : 0;
        passnode.getChildByName('level').getComponent(cc.Label).string = s
        var icon = passnode.getChildByName('icon').getComponent(cc.Sprite)
        icon.node.active = false;
        this.createImage(lastData.avatarUrl, function (spriteFrame) {
            this.spriteFrame = spriteFrame
            this.node.active = true;
        }.bind(icon))
    },

    showRank(data) {
        if (!data) {
            return;
        }
        cc.log('无尽排行数据', data);
        this.node.getChildByName('btnArr').active = true;
        this.btnShowArr[0].active = false;
        this.btnShowArr[1].active = true;
        this.node.getChildByName('scrollview').active = true;
        var self = this;
        function setItem(userItem, r, d) {
            userItem.getChildByName('name').getComponent(cc.Label).string = d.nickname;
            let grade = d.KVDataList[0] ? d.KVDataList[0].value : 0;
            userItem.getChildByName('score').active = true;
            userItem.getChildByName('level').active = false;
            userItem.getChildByName('score').getChildByName('level').getComponent(cc.Label).string = grade;
            userItem.getChildByName('rank').active = true;
            userItem.getChildByName('rank').getComponent(cc.Label).string = r;
            userItem.getChildByName('sex').getComponent('UI-Toggle').setToggle(parseInt(d.sex))

            var icon = userItem.getChildByName('icon').getComponent(cc.Sprite)
            icon.node.active = false;
            self.createImage(d.avatarUrl, function (spriteFrame) {
                this.spriteFrame = spriteFrame
                this.node.active = true;
            }.bind(icon))
        }

        this.node.active = true;
        this.rankContent.removeAllChildren();
        for (var i = 0; i < data.length; i++) {
            let userItem = cc.instantiate(this.rankItem);
            this.rankContent.addChild(userItem);
            setItem(userItem, i + 1, data[i])
            if (data[i].openid == this.openId) {
                // setItem(this.node.getChildByName('RankItem'), i + 1, data[i])
            }
        }
        // this.rankContent.getComponent(cc.Widget).updateAlignment();
        console.log('showRank:', data.length, ',height:', this.rankContent.height)
        this._hasRenderwuJinList = true;
    },


    showLevelRank(data) {
        if (!data) {
            return;
        }
        this.node.getChildByName('btnArr').active = true;
        this.btnShowArr[0].active = true;
        this.btnShowArr[1].active = false;
        this.node.getChildByName('levelscrollview').active = true;
        var self = this;
        function setItem(userItem, r, d) {
            userItem.getChildByName('name').getComponent(cc.Label).string = d.nickname;
            let level = d.KVDataList[0] ? JSON.parse(d.KVDataList[0].value).plotId : 0;
            userItem.getChildByName('score').active = false;
            userItem.getChildByName('level').active = true;
            userItem.getChildByName('rank').active = false;
            userItem.getChildByName('level').getChildByName('level').getComponent(cc.Label).string = '第' + level + '关';
            // userItem.getChildByName('rank').getComponent(cc.Label).string = r;
            userItem.getChildByName('sex').getComponent('UI-Toggle').setToggle(parseInt(d.sex))

            var icon = userItem.getChildByName('icon').getComponent(cc.Sprite)
            icon.node.active = false;
            self.createImage(d.avatarUrl, function (spriteFrame) {
                this.spriteFrame = spriteFrame
                this.node.active = true;
            }.bind(icon))
        }

        this.node.active = true;
        this.levelRankContent.removeAllChildren();
        for (var i = 0; i < data.length; i++) {
            let userItem = cc.instantiate(this.rankItem);
            this.levelRankContent.addChild(userItem);
            setItem(userItem, i + 1, data[i])
            if (data[i].openid == this.openId) {
                // setItem(this.node.getChildByName('RankItem'), i + 1, data[i])
            }
        }
        // this.rankContent.getComponent(cc.Widget).updateAlignment();
        console.log('showRank:', data.length, ',height:', this.levelRankContent.height)
        this._hasRenderLevelList = true;
    },
    onClick(event, data) {
        cc.log(data);
        this.node.getChildByName('btnArr').active = true;
        if (data == 1) {  //  关卡排名
            this.btnShowArr[0].active = true;
            this.btnShowArr[1].active = false;
            this.node.getChildByName('scrollview').active = false;
            if (this._hasRenderLevelList) {
                this.node.getChildByName('levelscrollview').active = true;
            } else {
                this.fetchLevelData('level', this.showLevelRank.bind(this));
            }

        } else if (data == 2) {    //无尽排名
            this.btnShowArr[0].active = false;
            this.btnShowArr[1].active = true;
            this.node.getChildByName('levelscrollview').active = false;
            if (this._hasRenderwuJinList) {
                this.node.getChildByName('scrollview').active = true;
            } else {
                this.fetchFriendData('score', this.showRank.bind(this));
            }
        }
    },

    createImage(avatarUrl, cb) {
        if (CC_WECHATGAME) {
            try {
                let image = wx.createImage();
                image.onload = () => {
                    try {
                        let texture = new cc.Texture2D();
                        texture.initWithElement(image);
                        texture.handleLoadedTexture();
                        cb(new cc.SpriteFrame(texture));
                    } catch (e) {
                        cb(null)
                    }
                };
                image.src = avatarUrl;
            } catch (e) {
                cb(null)
            }
        } else {
            cc.loader.load({
                url: avatarUrl, type: 'jpg'
            }, (err, texture) => {
                cb(new cc.SpriteFrame(texture))
            });
        }
    },

    showFriendHead(data) {
        cc.log('子域数据', data);
        this.resetScene();
        this.node.getChildByName('content').active = true;

        for (var key in this.positionData) {
            this.positionData[key].count = 0;
        };

        for (let i = 0; i < data.length; i++) {
            if (data[i].KVDataList.length > 0) {
                cc.log('有玩家进来了');
                let headImage = cc.instantiate(this.headImage);
                this.content.addChild(headImage);
                let plotId = (JSON.parse(data[i].KVDataList[0].value).plotId);
                let position = this.positionData[plotId];
                this.positionData[plotId].count++;
                let differX = ((this.positionData[plotId].count - 1) % 2) * (-1) * this.positionData[plotId].count * 25 + 15;
                let differY = position.bossPass ? 100 : 80;
                headImage.x = position.x + differX;
                headImage.y = position.y + differY;
                this.createImage(data[i].avatarUrl, function (spriteFrame) {
                    cc.log('产生的新的图片', headImage)
                    this.getChildByName('headImage').getComponent(cc.Sprite).spriteFrame = spriteFrame
                    this.active = true;
                }.bind(headImage))
            }
        }
    },


    // update (dt) {},
});
